<template>
  <form id="submitImgForm"
    method="post" 
    enctype="multipart/form-data" 
    :action="url">
    <label class="single-upload-wrap" :class="{disabled: disabled}" :style="{width: `${width}px`, height: `${height}px`, 'line-height': `${height}px`, 'font-size': `${width * .11}px`}">
      <span v-if="disabled">暂未上传图片</span>
      <span v-else>点击上传图片</span>
      <input type="file" 
        name="imgFile"
        :disabled="disabled"
        @change="onChangeFile">
        <img :src="imageSrc" v-show="imageSrc">
    </label>
  </form>
</template>

<script>
  export default {
    props: {
      imgsrc: [String], // 图片地址
      url: [String], // 图片上传URL地址
      width: {
        type: Number,
        default: 200
      },
      height: {
        type: Number,
        default: 100
      },
      disabled: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        imageSrc: this.imgsrc
      }
    },
    methods: {
      // 选择图片
      onChangeFile(ev) {
        const imgVal = ev.target.value || ''
        if (!/.jpg|.jepg|.png/i.test(imgVal)) {
          this.$toast('图片格式无效，请重新选择')
          return
        }
        $('#submitImgForm').ajaxSubmit(data => {
          this.imageSrc = JSON.parse(data).url
          this.$emit('on-upload', this.imageSrc)
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .single-upload-wrap {
    position: relative;
    display: block;
    width: 100%;
    height: 100%;
    text-align: center;
    color: #999;
    border-radius: 4px;
    border: 2px dashed #e6e6e6;
    background-color: #fafafa;
    cursor: pointer;
    &.disabled {
      cursor: not-allowed;
    }
    img {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: #fafafa;
    }
    input {
      width: 0;
      height: 0;
      opacity: 0;
    }
  }
</style>